import axios from "axios";
import { useUserStore } from "@/stores/user.js";
import router from "@/router";

import { ElMessage } from "element-plus";
// const baseUrl = "http://big-event-vue-api-t.itheima.net";
const baseUrl = "/api";

const instance = axios.create({
  baseURL: baseUrl,
  timeout: 10000,
});
// 请求拦截
instance.interceptors.request.use(
  (config) => {
    const useStore = useUserStore();
    if (useStore.token) {
      config.headers["Authorization"] = useStore.token;
    }

    return config;
  },
  (err) => {
    Promise.reject(err);
  }
);
// 响应拦截
instance.interceptors.response.use(
  (res) => {
    console.log(res, "响应拦截");
    if (res.status === 200) {
      return res.data;
    }
    if (res.data.code === -1) {
      Message.error("token过期，请重新登录");
      router.push("/login");
    }
  },
  (error) => {
    return Promise.reject(error);
  }
);
export default instance;
export { baseUrl };
